package com.masasdani.paypal.service;

import com.masasdani.paypal.config.PaypalConfig;
import com.masasdani.paypal.config.PaypalPaymentIntent;
import com.masasdani.paypal.config.PaypalPaymentMethod;
import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PaymentService {

	@Autowired
	private PaypalConfig paypalConfig;
	
	public Payment createPayment(
			Double total, 
			String currency, 
			PaypalPaymentMethod method, 
			PaypalPaymentIntent intent, 
			String description, 
			String cancelUrl, 
			String successUrl) throws PayPalRESTException{

		// Initialize apiContext with proper credentials and environment.
		APIContext apiContext = new APIContext(paypalConfig.getClientId(), paypalConfig.getClientSecret(), paypalConfig.getMode());
		// Set payment details
		/*Details details = new Details();
		details.setShipping("1");
		details.setSubtotal("5");
		details.setTax("1");*/


		Amount amount = new Amount();
		amount.setCurrency(currency);
		amount.setTotal(String.format("%.2f", total));

//		amount.setDetails(details);

		//         Set payment details
		// Details details = new Details();
		// details.setShipping("1");
		// details.setSubtotal("5");
		// details.setTax("1");
		// amount.setDetails(details);



		Transaction transaction = new Transaction();
		transaction.setDescription(description);
		transaction.setAmount(amount);

		List<Transaction> transactions = new ArrayList<>();
		transactions.add(transaction);

		Payer payer = new Payer();
		payer.setPaymentMethod(method.toString());

		Payment payment = new Payment();
		payment.setIntent(intent.toString());
		payment.setPayer(payer);
		payment.setTransactions(transactions);

		RedirectUrls redirectUrls = new RedirectUrls();
		redirectUrls.setCancelUrl(cancelUrl);
		redirectUrls.setReturnUrl(successUrl);
		payment.setRedirectUrls(redirectUrls);

		return payment.create(apiContext);
	}
	
	public Payment executePayment(String paymentId, String payerId) throws PayPalRESTException{
		// Initialize apiContext with proper credentials and environment.
		APIContext apiContext = new APIContext(paypalConfig.getClientId(), paypalConfig.getClientSecret(), paypalConfig.getMode());
		Payment payment = new Payment();
		payment.setId(paymentId);
		PaymentExecution paymentExecute = new PaymentExecution();
		paymentExecute.setPayerId(payerId);
		return payment.execute(apiContext, paymentExecute);
	}
}
